"""
Case Type   : 资源池化
Case Name   : 系统函数ss_buffer_ctrl函数字段及功能验证
Create At   : 2024.6
Owner       : haomeng
Description :
    1、查询特定的buffer的buf_ctrl信息
    2、查询DMS页面分布式锁不为NULL的buffer数量
    3、查询以S锁的方式持有页面的buf_ctrl信息
    4、查询以X锁的方式持有页面的buf_ctrl信息
    5、S锁+X锁的合计数量与不为NULL的数量一致
Expect      :
    1、查询成功
    2、查询成功
    3、查询成功
    4、查询成功
    5、对比成功，结果一致相等
"""

import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class SharedStorage(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')

        self.log.info('------检查数据库状态是否正常------')
        status = self.pri_sh.exec_cm_ctl('query', '-Cv')
        self.assertIn("cluster_state   : Normal", status)

    def test_innerfunc(self):
        text = '-----step1:查询特定的buffer的buf_ctrl信息; expect:查看成功-----'
        self.log.info(text)

        sql1 = 'select * from ss_buffer_ctrl() where bufferid = 20;'
        self.log.info(sql1)
        res1 = self.pri_sh.execut_db_sql(sql1)
        self.log.info(res1)
        self.assertIn('(1 row)', res1, '查看特定buffer的buf_ctrl信息失败')

        text = '-----step2:查询DMS页面分布式锁不为NULL的buffer数量; expect:查看成功-----'
        self.log.info(text)

        sql2 = 'select count(*) from ss_buffer_ctrl() where lock_mode > 0;'
        self.log.info(sql2)
        res2 = self.pri_sh.execut_db_sql(sql2)
        self.log.info(res2)
        self.assertNotEqual('0', res2.splitlines()[-2], '查看不为NULL的buffer信息失败')

        text = '-----step3:查询以S锁的方式持有页面的buf_ctrl信息; expect:查看成功-----'
        self.log.info(text)

        sql3 = 'select count(*) from ss_buffer_ctrl() where lock_mode = 1;'
        self.log.info(sql3)
        res3 = self.pri_sh.execut_db_sql(sql3)
        self.log.info(res3)
        self.assertNotEqual('0', res3.splitlines()[-2], '查看S锁方式持有页面的buf_ctrl信息失败')

        text = '-----step4:查询以X锁的方式持有页面的buf_ctrl信息; expect:查看成功-----'
        self.log.info(text)

        sql4 = 'select count(*) from ss_buffer_ctrl() where lock_mode = 2;'
        self.log.info(sql4)
        res4 = self.pri_sh.execut_db_sql(sql4)
        self.log.info(res4)
        self.assertNotEqual('0', res4.splitlines()[-2], '查看S锁方式持有页面的buf_ctrl信息失败')

        text = '-----step5:S锁+X锁的合计数量与不为NULL的数量一致; expect:对比结果一致相等-----'
        self.log.info(text)

        res_all = int(res3.splitlines()[-2]) + int(res4.splitlines()[-2])
        self.assertEqual(int(res2.splitlines()[-2].strip()), res_all, '结果不一致')

    def tearDown(self):
        text = '-----No need to clean-----'
        self.log.info(text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
